package com.ytsky.hctechnologysys.controller;
import com.github.pagehelper.PageInfo;
import com.ytsky.hctechnologysys.entity.Educate;
import com.ytsky.hctechnologysys.service.EducateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dell
 */
@Controller
public class EducateController {

    private  static final Logger logger = LoggerFactory.getLogger(EducateController.class);


    @Autowired
    private EducateService educateService;

    /**
     *返回培训人员信息添加界面
     * @return
     */
    @GetMapping("/educate/trainingchangeADD")
    public ModelAndView trainingchangeAddView(){
        ModelAndView mav = new ModelAndView("educate/trainingchangeADD");
        return  mav;

    }


    /**
     * 返回培训人员信息修改页面
     * @return
     */
    @GetMapping("/educate/trainingchanged")
    public ModelAndView trainingChangeView(
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword",required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("educate/trainingchanged");
        PageInfo<Educate> page =  educateService.findByKeyword(pageNum,pageSize,keyword);
        mav.addObject("page",page);
        return mav;
    }



    @GetMapping("/educate/trainingModify")
    public  ModelAndView trainingModifyView(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("educate/trainingModify");
        Educate educate = educateService.findById(id);
        mav.addObject("educate",educate);
        return mav;
    }

    @GetMapping("/educate/trainingRemove")
    public  ModelAndView trainingRemove(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    )throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/educate/trainingchanged?pageNum="+ pageNum  +
                "&pageSize=" + pageSize +
                "&keyword" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = educateService.remove(id);
        return mav;
    }


    @PostMapping("/educate/trainingchangeADD")
    public ModelAndView trainingAdd(@Validated Educate educate, BindingResult bindingResult){
        //redirect表示重定向响应
        //给浏览器发送一个请求地址，而没有任何视图内容或数据
        //浏览器会使用收到的地址，重新发送一个Get请求，由于是新请求，因此没有缓存上一次请求的数据，从而达到防止重复提交表单的目的
        ModelAndView mav = new ModelAndView("redirect:/educate/trainingchangeADD");

        Map<String,String> errorMessages = new HashMap<>();
        if (bindingResult.hasErrors()){
            //如果由验证错误消息，那么要进行处理
            //获得出现错误域，以及相应的错误消息文本
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //错误信息放入到映射中
            for (FieldError error : fieldErrors){
                //从每一个域错误对象中取出域名称，错误消息，加到映射集合中
                errorMessages.put(error.getField(),error.getDefaultMessage());
            }
            //将错误信息发送给视图
            mav.addObject("errorMessages",errorMessages);
            //将客户填写的而信息，重新显示在表单中
            mav.addObject("educate",educate);
            //由于没有保存数据，因此不必进行重定向，内部转发请求到视图，同时还要保留请求数据，以及相应的信息
            mav.setViewName("/educate/trainingchangeADD");
        }else{
            //如果没有错误信息，验证通过
            //调用服务方法保存客户数据
            boolean result = educateService.append(educate);
            if (result){
                logger.info("新增员工培训信息成功 - "+educate);
            }else{
                logger.info("新增员工培训信息失败 - "+educate);
            }
        }
        return  mav;
    }


    @PostMapping("/educate/trainingModify")
    public ModelAndView trainingModify(
            Educate educate,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "100") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/educate/trainingchanged?pageNum="+ pageNum  +
                "&pageSize=" + pageSize +
                "&keyword" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = educateService.modify(educate);
        System.out.println(result);
        return mav;

    }
}
